<?php
class Wiki_Controller_Plugin_Cache extends Zend_Controller_Plugin_Abstract {
	
	private $doCache = true;
	private $cache;
	private $key;
	
	public function __construct($options) {
		if ($options instanceof Zend_Config) {
			$options = $options->toArray();
		}
		
		if (!is_array($options)) {
			throw new Exception('Invalid cache options. Must be array or Zend_Config object.');
		}
		
		if (array('frontend', 'backend', 'frontendOptions', 'backendOptions') != array_keys($options)) {
			throw new Exception('Invalid cache options. Only frontend, backend, frontendOptions and backendOptions are allowed.');
		}
		
		$options['frontendOptions']['automatic_serialization'] = true;
		
		$this->cache = Zend_Cache::factory(
			$options['frontend'],
			$options['backend'],
			$options['frontendOptions'],
			$options['backendOptions']
		);
	}
	
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
		if (!$request->isGet()) {
			$this->doCache = false;
			return;
		}
		
		$this->key = md5($request->getPathInfo());
		
		if (false !== ($response = $this->cache->load($this->key))) {
			$response->sendResponse();
			exit;
		}
	}
	
	public function dispatchLoopShutdown() {
		if (!$this->doCache || $this->getResponse()->isRedirect() || ($this->key === null)) {
			return;
		}
		
		$this->cache->save($this->getResponse(), $this->key);
	}
	
	public function setCaching($doCache) {
		$this->doCache = $doCache;
	}
}